package com.googlecode.cswish.struts;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.DefaultStaticContentLoader;

import com.googlecode.cswish.util.FrameConstant;

public class StaticContentLoader extends DefaultStaticContentLoader {

	@Override
	public boolean canHandle(String resourcePath) {
        return serveStatic && (resourcePath.startsWith("/static/"));
    }
	
	@Override
	public void findStaticResource(String path, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        URL resourceUrl = findResource(path);
        if (resourceUrl != null) {
            InputStream is = null;
            try {
                //check that the resource path is under the pathPrefix path
                String pathEnding = URLDecoder.decode(path, encoding);
                if (resourceUrl.getFile().endsWith(pathEnding))
                    is = resourceUrl.openStream();
            } catch (IOException ex) {
                // just ignore it
            }

            //not inside the try block, as this could throw IOExceptions also
            if (is != null) {
                process(is, path, request, response);
                return;
            }
        }        
        
        //response.sendError(HttpServletResponse.SC_NOT_FOUND);
        request.setAttribute(FrameConstant.STATIC_NOT_FOUND, true);
	}
}
